/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.service.manage;

import cn.ac.nercis.pes.common.utils.PasswordUtils;
import cn.ac.nercis.pes.model.dto.common.Result;
import cn.ac.nercis.pes.model.dto.common.ResultCode;
import cn.ac.nercis.pes.model.dto.manage.UserDTO;
import cn.ac.nercis.pes.repository.dal.manage.UserRepository;
import cn.ac.nercis.pes.repository.mapper.manage.UserMapper;
import cn.ac.nercis.pes.repository.model.base.DeleteFlag;
import cn.ac.nercis.pes.repository.model.manage.UserDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 身份认证服务
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
@Service
public class AuthService {
    private final UserRepository userRepository;

    @Autowired
    public AuthService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Result<UserDTO> login(String userName, String pwd){
        UserDO user = userRepository.findByUsername(userName).orElse(null);
        if(Objects.isNull(user) || user.getDeleteFlag() == DeleteFlag.DELETED){
            return Result.failed(ResultCode.USER_NOT_EXIST);
        }
        return validInternalUser(user,pwd);
    }

    private Result<UserDTO> validInternalUser(UserDO user,String loginPwd){
        if(StringUtils.equals(user.getPassword(), PasswordUtils.encryption(loginPwd))){
            user.setWebServer(false);
            return Result.success(UserMapper.INSTANCE.toDTO(user));
        }else{
            return Result.failed(ResultCode.USER_PWD_ERROR);
        }
    }


}